package com.lsh.payment.core.strategy.bill;

import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.strategy.config.MisPayConfig;
import com.lsh.payment.core.strategy.vo.mispurse.BillDetail;
import com.lsh.payment.core.strategy.vo.mispurse.MisBillResponse;
import com.lsh.payment.core.util.DateUtil;
import com.lsh.payment.core.util.HttpClientUtils;
import com.lsh.payment.core.util.PathUtil;
import com.lsh.payment.core.util.pay.wxpay.WxSignature;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 16/11/24
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
public class MisPurseBillStrategy implements BillStrategy {

    private final String FILEHEAD = "钱包订单号,外部订单号,支付类型,订单支付金额,订单类型,系统交易时间";

    private final String FILEEND = "总笔数,总金额";

    private final String LINE_SEPARATOR = ",";

    private static final String BILL_DOWNLOAD = "/trade/info/getListByDate";

    private static Logger logger = LoggerFactory.getLogger(MisPurseBillStrategy.class);

    /**
     * 下载对账单
     *
     * @param billDate 查询参数
     * @param billType
     * @return
     */
    @Override
    public boolean downloadBillByDate(String billDate, int billType) {
        String prefix = "【请求mis下载对账单】 ";

        if(StringUtils.isBlank(billDate)){
            billDate = DateUtil.getYesterdayStr();
        }

        if (StringUtils.isBlank(billDate)) {
            return false;
        }

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("appid", MisPayConfig.APPID);
        params.put("date", billDate);

        int timestamp = (int) (System.currentTimeMillis() / 1000);

        String sign = WxSignature.getMisSign(params, MisPayConfig.APPID, timestamp);

        Map<String, String> headMap = new HashMap<>();

        headMap.put("timestamp", timestamp + "");
        headMap.put("accesskey", MisPayConfig.APPID);
        headMap.put("sign", sign);

        String billFileName = MessageFormat.format(MisPayConfig.MIS_PURSE_BILL_NAME, billDate);

        try {

            String url = MisPayConfig.PAY_API + BILL_DOWNLOAD;

            logger.info(prefix + "【download bill start】");
            String billMessage = HttpClientUtils.doGet(url, params, headMap);
            logger.info(prefix + "【download bill end】");
            if (StringUtils.isBlank(billMessage)) {
                return false;
            }

            MisBillResponse misBillResponse = JSON.parseObject(billMessage, MisBillResponse.class);

            if (0 != misBillResponse.getRet()) {
                return false;
            }

            List<BillDetail> billDetails = misBillResponse.getContent();

            if (CollectionUtils.isEmpty(billDetails)) {
                billDetails = new ArrayList<>();
            }

            this.writeFile(billDetails, billFileName);
        } catch (Exception e) {
            logger.error("钱包下载对账单失败", e);
            throw new BusinessException(ExceptionStatus.E2004009.getCode(), ExceptionStatus.E2004009.getMessage());
        }

        return false;
    }


    /**
     * 写文件
     *
     * @param billDetails 查询出的数据列表
     * @param fileName    文件名称
     * @return 返回对象
     */
    private void writeFile(List<BillDetail> billDetails, String fileName) {
        FileOutputStream outputStream = null;
        try {
            String downLoadPath = BusinessConstant.BILL_DOWNLOAD_PATH_PURSE + File.separator + DateUtil.getDateString();
            PathUtil.createPath(downLoadPath);
            File file = new File(downLoadPath + File.separator + fileName);
            outputStream = new FileOutputStream(file);
            //写文件头
            outputStream.write((FILEHEAD + System.getProperty("line.separator")).getBytes("UTF-8"));
            //写内容
            int sumCount = 0;
            BigDecimal sumAmount = BigDecimal.ZERO;
            StringBuffer sLines = new StringBuffer();
            //钱包订单号,外部订单号,支付类型,订单支付金额,订单类型(1.收入，2.退款),系统交易时间
            //支付类型 3.purse_on_credit_pay 4.purse_pre_pay  2.purse_balance_pay
            for (BillDetail detail : billDetails) {
                StringBuffer sLine = new StringBuffer();
//                sLine.append(detail.getAppid()).append(LINE_SEPARATOR);
                sLine.append(detail.getTrade_id()).append(LINE_SEPARATOR);
                sLine.append(detail.getOut_trade_no()).append(LINE_SEPARATOR);
                sLine.append(detail.getPay_method()).append(LINE_SEPARATOR);
//                sLine.append(detail.getChannel_type()).append(LINE_SEPARATOR);
                sLine.append(detail.getTrade_money()).append(LINE_SEPARATOR);
                sLine.append(detail.getType()).append(LINE_SEPARATOR);
                sLine.append(detail.getCreated_at()).append(LINE_SEPARATOR);

                sLines.append(sLine).append(System.getProperty("line.separator"));

                sumCount++;
                sumAmount = sumAmount.add(detail.getTrade_money());
            }
            outputStream.write(sLines.toString().getBytes("UTF-8"));

//            //写文件尾
            String fileE = FILEEND + System.getProperty("line.separator") + sumCount + LINE_SEPARATOR + sumAmount + System.getProperty("line.separator");
            outputStream.write(fileE.getBytes("UTF-8"));

        } catch (Exception e) {
            logger.error("write file fail", e);
            throw new BusinessException(ExceptionStatus.E2004009.getCode(), ExceptionStatus.E2004009.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
